package com.example.client.controller;

import com.example.client.listen.WebSocketClientEndpoint;
import jakarta.websocket.ContainerProvider;
import jakarta.websocket.Session;
import jakarta.websocket.WebSocketContainer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.net.URI;

@RestController
@RequestMapping("/api")
@Slf4j
public class FileController {

    @Autowired
    private WebSocketClientEndpoint webSocketClientEndpoint;

    @PostMapping("/upload")
    public void uploadFile(@RequestParam("file") MultipartFile file) throws Exception {
        // 创建WebSocket客户端
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        String uri = "ws://speech.xiaoyuzhineng.com:12392"; // 请替换为实际的WebSocket服务器URI
        String param = "?apikey=" + "DTV5vw0Pe"
                + "&ts=" + String.valueOf(System.currentTimeMillis()/1000)
                + "&lang=zh"
                + "&continuous_decoding=" + "True";
        Session session = container.connectToServer(WebSocketClientEndpoint.class, URI.create(uri+param));
        // 上传文件并发送到WebSocket服务器
//        Path filePath = Path.of("/Users/zhouhailong/Documents/请求流程（协同）.jpg"); // 请替换为实际的文件路径
        byte[] fileBytes = file.getBytes();
        int chunkSize = 1024 * 6;
        for (int i = 0; i < fileBytes.length; i += chunkSize) {
            int endIndex = Math.min(i + chunkSize, fileBytes.length);
            byte[] chunk = new byte[endIndex - i];
            System.arraycopy(fileBytes, i, chunk, 0, chunk.length);
            // 使用WebSocket客户端发送文件块
//            log.info("发送音频流，当前时间戳,{}",System.currentTimeMillis());
            webSocketClientEndpoint.sendByteMessage(session,chunk);
            Thread.sleep(80);
        }
        webSocketClientEndpoint.sendTextMessage(session,"EOF");
        session.close();
//        webSocketClientEndpoint.sendTextMessage(session,"hello world");
    }

}
